#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Download available firmware update for OSRAM/LEDVANCE
# ==============================================================================
readonly URL_OSRAM="https://api.update.ledvance.com/v1/zigbee/firmwares"

# Ensure OTAU folder exists
mkdir -p "/data/otau"

bashio::log.info "Running the OSRAM/LEDVANCE OTA updater..."

# Fetch OSRAM/LEDVANCE firmware data
if ! OSRAM_DATA="$(curl -sL ${URL_OSRAM})"; then
    bashio::log.warning "⚠️ Can't fetch data from OSRAM/LEDVANCE — retry in 5 hours."
    exec sleep 18000
fi

OSRAM_DATA_SIZE="$(echo "${OSRAM_DATA}" | jq --raw-output '.firmwares | length')"
for (( i=0; i < OSRAM_DATA_SIZE; i++ )); do
    OSRAM_COMPANY=$( echo "${OSRAM_DATA}" | jq --raw-output ".firmwares[$i].identity.company  // empty" 2>/dev/null)
    OSRAM_PRODUCT=$( echo "${OSRAM_DATA}" | jq --raw-output ".firmwares[$i].identity.product  // empty" 2>/dev/null)
    OTAU_FILENAME=$( echo "${OSRAM_DATA}" | jq --raw-output ".firmwares[$i].name  // empty" 2>/dev/null)
    OTAU_URL="$URL_OSRAM/download/${OSRAM_COMPANY}/${OSRAM_PRODUCT}/latest"
    OTAU_FILE="/data/otau/${OTAU_FILENAME}"

    # Skip empty file names
    [[ -z "${OTAU_FILENAME}" ]] && continue

    # Skip already downloaded files
    [[ -e "${OTAU_FILE}" ]] && continue

    # Download firmware
    curl -s -L -o "${OTAU_FILE}" "${OTAU_URL}" || true
    sleep 5 # OSRAM/LEDVANCE API rate limits: The limit is 30 requests per minute.
done

exec sleep 273600 # Sleep for 3 days 4 hours before next check
